package nowCoder;

import java.util.*;

/**
 * Created by Ghost on 2015/1/26 0026.
 */
class Bag implements Comparable {
    int a;
    int n;
    Bag(int a, int n){
        this.a = a;
        this.n = n;
    }

    @Override
    public int compareTo(Object o) {
        Bag b = (Bag) o;
        return b.n-this.n;
    }
}
public class Multinomial {
    List<Bag> aa = new LinkedList<Bag>();
    List<Bag> bb = new LinkedList<Bag>();

    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    public void init(String a,String b){
        String[] as = a.split("\\),\\(");
        String[] bs = b.split("\\),\\(");
        if(as.length>0){
            as[0] = as[0].replace("(","");
            as[as.length-1] = as[as.length-1].replace(")","");
        }
        if(bs.length>0){
            bs[0] = bs[0].replace("(","");
            bs[bs.length-1] = bs[bs.length-1].replace(")","");
        }

        for(String s:as){
            String[] s1 = s.split(",");
            Bag b1 = new Bag(Integer.parseInt(s1[0]),Integer.parseInt(s1[1]));
            aa.add(b1);
        }
        for(String s:bs){
            String[] s1 = s.split(",");
            Bag b1 = new Bag(Integer.parseInt(s1[0]),Integer.parseInt(s1[1]));
            bb.add(b1);
        }
    }

    public void calculate(){
        for(Bag bag1:aa){
            for(Bag bag2:bb){
                int a = bag1.a*bag2.a;
                int n = bag1.n+bag2.n;
                if(map.containsKey(n)){
                    map.put(n,a + map.get(n));
                } else{
                    map.put(n,a);
                }
            }
        }
    }

    public String getRst(){
        List<Bag> rst = new LinkedList<Bag>();
        Set<Map.Entry<Integer, Integer>> entry = map.entrySet();
        for(Map.Entry<Integer, Integer> ent:entry){
            if(ent.getValue()!=0){
                rst.add(new Bag(ent.getValue(),ent.getKey()));
            }
        }
        if(rst.size()>0){
            Bag[] bags = new Bag[rst.size()];
            rst.toArray(bags);

            Arrays.sort(bags);
            StringBuilder sb = new StringBuilder("");
            for(int i=0;i<bags.length-1;i++){
                sb.append("(").append(bags[i].a).append(",").append(bags[i].n).append("),");
            }
            sb.append("(").append(bags[bags.length-1].a).append(",").append(bags[bags.length-1].n).append(")");
            return sb.toString();
        }
        else
            return "";
    }

    public static void main(String[] args){
        Multinomial mu = new Multinomial();
        mu.init("(2,3),(1,2),(5,0)","(0,2)");
        mu.calculate();
        String rst = mu.getRst();
        System.out.println(rst);
    }
}
